from Base.HTMLTestRunner import HTMLTestRunner
import os, time, unittest,re

from Base.Log import Log
from Test.DingTalkTest import SendText


log=Log()
dirpath = os.path.dirname(os.path.dirname(__file__))
casepath = os.path.join(dirpath, "TestCase")
#编写报告名称
reportName = "report" + time.strftime("%Y_%m_%d") + ".html"
reportpath = os.path.join(dirpath, 'CaseResult', reportName)
log.info("======开始运行自动化测试用例=======")
# print(reportpath)
#获取所有unittest框架下测试用例
all_cases = unittest.defaultTestLoader.discover(casepath, pattern='test*.py')
# webhook='https://oapi.dingtalk.com/robot/send?access_token=9e15605640eecb7a104818e492ec0c76fde38c0c4945849371376c0c9ff3a879'
print("all_cases",all_cases)
# runner = unittest.TextTestRunner()

fp = open(reportpath, 'wb')
runner = HTMLTestRunner(stream=fp,
                        title='Tpson接口自动化测试报告', #测试报告标题
                        description='Tpson接口自动化测试报告',
                        )
#运行测试用例获取测试结果
result=runner.run(all_cases)
fp.close()
print("测试",result)
run_all = re.findall("run=(.*?) error",str(result))[0]
run_errors = re.findall("errors=(.*?) f",str(result))[0]
run_failures = re.findall("failures=(.*?)>",str(result))[0]
run_success=str(int(run_all)-int(run_errors)-int(run_failures))
# result_list=re.findall(r'run="(.*?)" error',str(result))
# print(run_all)
msg = '测试结果：共运行了%s条用例，成功了%s条用例，报错了%s条用例,失败了%s条用例,具体详情请查看已生成测试报告'%(run_all,run_success,run_errors,run_failures)
log.info("======自动化测试完成=========")
print(msg)
# send_text = SendText(webhook)
# send_text.send_text(msg=msg)
